<?php
namespace GrouppaGroup;
class MessageFromServer
{
    private static $lastId = 0;
    /**
     * serialized in JSON arguments of response
     * @var string
     */
    public $serializedArguments;
    /**
     * id of server message
     * @var integer
     */
    public $id;
    /**
     * id of app message to which this one is response
     * @var integer
     */
    public $responseToId;
    /**
     * name of the controller which sends this message
     * @var string
     */
    public $fromController;
    /**
     * name of the controller which ought to receive this message
     * @var string
     */
    public $toController = '';
    /**
     * name of the task on Application which should be run
     * @var string
     */
    public $toTask = '';

    /**
     * message type of calling message (if available)
     * used to identify response to messages
     * decided by the client, copied from MessageFromApp
     * @var string
     */
    public $messageType;

    /**
     * is the response good or not
     * @var boolean
     */
    public $statusOK = true;

    /**
     * gets a new unique id for this message
     * @return integer
     */
    protected static function getNewId()
    {
        //TODO: get message id from database, or is it necessary?
        return ++self::$lastId;
    }

    public function __construct($serializedArguments = '', $fromController = '', $messageType =
        '', $responseToId = -1)
    {
        $this->id = self::getNewId();
        $this->serializedArguments = $serializedArguments;
        $this->fromController = $fromController;
        $this->messageType = $messageType;
        $this->responseToId = $responseToId;

    }

    /**
     * converts this message to JSON
     * @return string with message encoded in JSON
     */
    public function getJSON()
    {
        $status = $this->statusOK ? "true" : "false";
        $args = $this->serializedArguments ? $this->serializedArguments : "\"\"";
        $json = <<< EOT
{
    "id":{$this->id},
    "serializedArguments":{$args},
    "responseToId":{$this->responseToId},
    "fromController":"{$this->fromController}",
    "toController":"{$this->toController}",
    "toTask":"{$this->toTask}",
    "messageType":"{$this->messageType}",
    "statusOK":{$status}
}
EOT;

        return $json;
    }

}
